package com.yboot.ssocas.login;

import org.jasig.cas.client.util.AssertionHolder;
import org.jasig.cas.client.validation.Assertion;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDateTime;

@Controller
public class Login {

    private static String ip="http://192.168.1.101";

    @RequestMapping(value = {"/cas/login","/"})
    @ResponseBody
    public void cas(HttpServletRequest request_ ,HttpServletResponse response_) throws IOException {
        HttpSession session = request_.getSession();
        String jsessionid = session.getId();
        System.out.println("jsessionid ------> " + jsessionid);
        String loginName_ = CASUtil.getAccountNameFromCas(request_);
        System.out.println("CASUtil =>loginName_ : "+loginName_);
        System.out.println("cas = " + LocalDateTime.now());
        // 跳转到前端
        response_.sendRedirect(ip+":8001/web?jsessionid=" + jsessionid);
    }

    @RequestMapping("/v1/test")
    @ResponseBody
    public String test(HttpServletRequest request_ ){
        //路径不同不进行拦截
        System.out.println("test = "+ LocalDateTime.now());
        return "test"+ LocalDateTime.now();
    }

    @RequestMapping("/cas/success")
    @ResponseBody
    public String success(HttpServletRequest request_ ){
        HttpSession session = request_.getSession();
        String jsessionid = session.getId();
        System.out.println("jsessionid ---success--> " + jsessionid);
        Assertion assertion = AssertionHolder.getAssertion();
        System.out.println("success = " + assertion.getPrincipal().getName());
        return "success";
    }

    @RequestMapping("/cas/logout")
    public String logout(HttpSession session,HttpServletRequest request, HttpServletResponse response){
        System.out.println("session = " + session);
        session.invalidate();
        Cookie[] cookies = request.getCookies();
        if(null !=cookies){
            for(int i=0;i<cookies.length;i++){
                if("JSESSIONID".equalsIgnoreCase(cookies[i].getName())){
                    cookies[i].setMaxAge(0);
                    response.addCookie(cookies[i]);
                }
            }
        }
        return "redirect:http://192.168.106.206:8086/nwsso/logout?service="+ip+":8001/jjhc/cas/login";
    }

}
